package com.smbms.servlet;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.smbms.pojo.Role;
import com.smbms.pojo.User;
import com.smbms.service.role.RoleService;
import com.smbms.service.role.RoleServiceImpl;
import com.smbms.service.user.UserService;
import com.smbms.service.user.UserServiceImpl;
import com.smbms.utils.Constant;
import com.smbms.utils.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 描述
 * @Author 羽落陌殇
 * @Date 2021/7/19 9:12
 * @Version 1.0.0
 */
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private RoleService roleService = new RoleServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (StrUtil.isNotBlank(method) && "savepwd".equals(method)) {
            updateUserPassword(req, resp);
        } else if (StrUtil.isNotBlank(method) && "pwdmodify".equals(method)) {
            validatePassword(req, resp);
        } else if (StrUtil.isNotBlank(method) && "query".equals(method)) {
            queryList(req,resp);
        } else if (StrUtil.isNotBlank(method) && "ucexist".equals(method)) {
            userCodeIsExists(req, resp);
        } else if (StrUtil.isNotBlank(method) && "getrolelist".equals(method)) {
            getRoleList(req, resp);
        } else if (StrUtil.isNotBlank(method) && "add".equals(method)) {
            createUser(req, resp);
        } else if (StrUtil.isNotBlank(method) && "modify".equals(method)) {
            queryUserById(req, resp);
        } else if (StrUtil.isNotBlank(method) && "modifyexe".equals(method)) {
            modifyUser(req, resp);
        } else if (StrUtil.isNotBlank(method) && "view".equals(method)) {
            showUser(req, resp);
        }  else if (StrUtil.isNotBlank(method) && "deluser".equals(method)) {
            deleteUser(req, resp);
        }

    }




    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 修改密码
    private void updateUserPassword(HttpServletRequest req, HttpServletResponse resp) {
        // 从Session中获取用户信息
        Object attribute = req.getSession().getAttribute(Constant.USER_SESSION);
        // 获取客户端的新密码
        String newPassword = req.getParameter("newpassword");
        if (ObjectUtil.isNotNull(attribute) && StrUtil.isNotEmpty(newPassword)) {
            int result = userService.updateUserPassword(((User) attribute).getId(), newPassword);
            if (result > 0) {
                req.setAttribute("message", "修改密码成功, 请退出系统, 使用新密码重新登录!");
                req.getSession().removeAttribute(Constant.USER_SESSION);
            } else {
                req.setAttribute("message", "修改密码失败, 请重新输入");
            }
        } else {
            req.setAttribute("message", "新密码有问题");
        }

        try {
            req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    // 验证旧密码
    private void validatePassword(HttpServletRequest req, HttpServletResponse resp) {
        Object attribute = req.getSession().getAttribute(Constant.USER_SESSION);
        String oldPassword = req.getParameter("oldpassword");
        // 万能的结果集: Map
        Map<String, String> resultMap = new HashMap<>();
        if (ObjectUtil.isNull(attribute)) { // Session失效了,登录过期了
            resultMap.put("result", "sessionerror");
        } else if (StrUtil.hasEmpty(oldPassword)) {
            resultMap.put("result", "error");
        } else {
            String userPassword = ((User) attribute).getUserPassword();
            if (userPassword.equals(oldPassword)) { // 判断旧密码的正确性
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }
        // 设置页面数据的返回格式为JSON格式
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 查询用户列表
    private void queryList(HttpServletRequest req, HttpServletResponse resp) {
        // 获取页面的数据
        String queryName = req.getParameter("queryname");
        String queryUserRoleTemp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;
        // 第一次走这个请求, 一定是第一页, 页面大小固定的
        int currentPageNo = 1;
        int pageSize = 5;
        if (queryName == null) {
            queryName = "";
        }
        if (StrUtil.isNotEmpty(queryUserRoleTemp)) {
            queryUserRole = Integer.parseInt(queryUserRoleTemp);
        }
        if (StrUtil.isNotEmpty(pageIndex)) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        System.out.println(queryName);
        // 获取用户的总数
        int totalCount = userService.getUserCount(queryName, queryUserRole);
        // 总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        // 控制首页和尾页
        // 获取总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        if (totalPageCount < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        // 获取角色列表
        List<Role> roleList = roleService.getRoleList();
        // 获取用户列表
        List<User> userList = userService.getUserList(queryName, queryUserRole, currentPageNo, pageSize);

        // 将查询出来的数据传递给前段
        req.setAttribute("roleList", roleList);
        req.setAttribute("userList", userList);

        // 将分页信息传递给前段
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);

        // 跳转回前端页面
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    // 根据 userCode 判断用户是否存在
    private void userCodeIsExists(HttpServletRequest req, HttpServletResponse resp) {
        Map<String, String> resultMap = new HashMap<>();
        String userCode = req.getParameter("userCode");
        if (StrUtil.isBlank(userCode)) {
            resultMap.put("userCode", "exist");
            return;
        }
        boolean result = userService.userNameIsExists(userCode);

        if (result) {
            resultMap.put("userCode", "exist");
        } else {
            resultMap.put("userCode", "notexist");
        }
        // 设置页面数据的返回格式为JSON格式
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取角色列表
    private void getRoleList(HttpServletRequest req, HttpServletResponse resp) {
        List<Role> roleList = roleService.getRoleList();
        // 设置页面数据的返回格式为JSON格式
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(roleList.toArray()));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 添加用户
    private void createUser(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("进入Add方法");
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        int createBy = -1;
        Map<String, String> resultMap = new HashMap<>();
        boolean userCodeIsExists = userService.userNameIsExists(userCode);
        Object attribute = req.getSession().getAttribute(Constant.USER_SESSION);
        if (ObjectUtil.isNotNull(attribute)) {
            createBy = ((User) attribute).getId();
        }
        if (!userCodeIsExists) {
            User user = new User(userCode, userName, userPassword,
                    Integer.parseInt(gender), Date.valueOf(birthday),
                    phone, address, Integer.parseInt(userRole), createBy, new java.util.Date());

            System.out.println(user.toString());
            int result = userService.createUser(user);
            System.out.println("result" + result);
            if (result > 0) {
                try {
                    resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 修改之查询用户信息并回显
    private void queryUserById(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        User user = null;
        if (StrUtil.isNotBlank(uid)) {
            user = userService.queryUserById(Integer.parseInt(uid));
        }
        req.setAttribute("user", user);
        try {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    // 修改用户
    private void modifyUser(HttpServletRequest req, HttpServletResponse resp) {
        // 表单中获取的数据
        String uid = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        // 当前登录的用户ID
        int sessionUserId = ((User) req.getSession().getAttribute(Constant.USER_SESSION)).getId();
        User user = new User(Integer.parseInt(uid), userName, Integer.parseInt(gender),
                Date.valueOf(birthday), phone,address, Integer.parseInt(userRole),
                sessionUserId, new java.util.Date());

        boolean result = userService.updateUser(user);
        if (result) {
            try {
                resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 展示用户信息
    private void showUser(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        User user = null;
        if (StrUtil.isNotBlank(uid)) {
            user = userService.queryUserById(Integer.parseInt(uid));
        }
        req.setAttribute("user", user);
        try {
            req.getRequestDispatcher("userview.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    // 根据用户ID 删除用户数据
    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        Map<String, String> resultMap = new HashMap<>();
        if (StrUtil.isBlank(uid)) {
            resultMap.put("delResult", "notexist");
            return;
        }
        boolean result = userService.deleteUser(Integer.parseInt(uid));
        if (result) {
            resultMap.put("delResult", "true");
        } else {
            resultMap.put("delResult", "false");
        }
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
